<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {ElMessage} from "element-plus";
import SIdentify from '@/components/login/Sidentify.vue'
import { useRouter } from 'vue-router'
import axios from "@/plugins/axios.js";
import $qs from "qs";
import router from "@/router/index.js";

const user = ref({
  userName: '',
  password: '',
  verify: ''
})
const loginForm = reactive({
  userName: [
    {required: true, message: '', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '', trigger: 'blur'}
  ],
  verify: [
    {required: true, message: '', trigger: 'blur'}
  ],
})

//获取路由器
let $router = useRouter()
let identifyCode = ref('') //图形验证码
let identifyCodes = ref('1234567890abcdefjhijklinopqrsduvwxyz') //验证码出现的数字和字母

//组件挂载
onMounted(() => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
})

// 生成随机数
const randomNum = (min, max) => {
  max = max + 1
  return Math.floor(Math.random() * (max - min) + min)
}
// 随机生成验证码字符串
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)]
  }
}
// 更新验证码
const refreshCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
}

const login = () => {
  if (user.value.userName === '') {
    ElMessage.error('请输入用户名')
  } else if (user.value.password === '') {
    ElMessage.error('请输入密码')
  } else if (user.value.verify === '') {
    ElMessage.error('请输入验证码')
  } else {
    if (user.value.verify === identifyCode.value) {
      axios.post('/api/auth/login',$qs.stringify(user.value)).then(res => {
        if (res.data.code === 200) {
          localStorage.setItem("creamDataToken", res.data.data.token)
          router.push("/home")
          ElMessage.success(res.data.message)
        } else {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      refreshCode()
      ElMessage({
        message: '验证码错误',
        type: 'error'
      })
    }
  }
}

const activeName = ref('first')

//注册功能
let code = ref('')
const registerForm = ref({
  userName: '',
  password: '',
  phone: '',
  code: ''
})
//发送验证码
const sendSms = () => {
  axios.post('/api/auth/sendSms?phone=' + registerForm.value.phone).then(res => {
    console.log(registerForm.value.phone)
    if (res.data.code === 200) {
      ElMessage.success(res.data.message)
      code.value = 60
    } else {
      ElMessage.error(res.data.message)
    }
  })
  // 倒计时
  let timer
  timer = setInterval(() => {
    code.value--
    if (code.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}
//注册方法
const register = () => {
  if (registerForm.value.userName === '') {
    ElMessage.error('请输入用户名')
  } else if (registerForm.value.password === '') {
    ElMessage.error('请输入密码')
  } else if (registerForm.value.phone === '') {
    ElMessage.error('请输入手机号')
  } else if (registerForm.value.code === '') {
    ElMessage.error('请输入验证码')
  } else {
    axios.post('/api/auth/register',$qs.stringify(registerForm.value)).then((res) =>{
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        activeName.value = 'first'
      } else {
        ElMessage.error(res.data.message)
      }
    })
  }
}


</script>

<template>

  <div id="login">
    <div id="contain">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="登录" name="first">
          <!-- 登录表单 -->
          <el-form :ref="loginForm" :model="user" :rules="loginForm" class="login_form" label-width="0px">
            <!--后端管理系统-->
            <p style="color:#73879C;font-size: 20px;">登录CreamData</p>
            <!-- 用户名 -->
            <el-form-item prop="userName">
              <el-input v-model="user.userName" class="textLogin" placeholder="用户名"></el-input>
            </el-form-item>
            <!-- 密码 -->
            <el-form-item prop="password">
              <el-input v-model="user.password" class="textLogin" placeholder="密码" type="password"></el-input>
            </el-form-item>
            <el-form-item prop="verify">
              <el-input v-model="user.verify" class="textLogin" placeholder="验证码"
                        style="width: 190px;height: 50px"></el-input>
              <SIdentify :identifyCode="identifyCode" @click="refreshCode()"></SIdentify>
            </el-form-item>
            <el-divider/>
            <!-- 按钮 -->
            <el-form-item>
              <el-button style="width: 300px;height: 40px;margin-left: 27px" type="primary" @click="login()">登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="注册" name="second">
          <!-- 登录表单 -->
          <el-form :ref="loginForm" :model="registerForm" :rules="loginForm" class="login_form" label-width="0px">
            <!--后端管理系统-->
            <p style="color:#73879C;font-size: 20px;">注册CreamData</p>
            <!-- 用户名 -->
            <el-form-item prop="userName">
              <el-input v-model="registerForm.userName" class="textLogin" placeholder="用户名"></el-input>
            </el-form-item>
            <!-- 密码 -->
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" class="textLogin" placeholder="密码" type="password"></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input v-model="registerForm.phone" class="textLogin" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <el-input v-model="registerForm.code" class="textLogin" placeholder="验证码"
                        style="width: 190px;"></el-input>
              <el-button :disabled="code > 0" @click="sendSms">{{ code > 0 ? code + 's' : '发送验证码' }}</el-button>
            </el-form-item>
            <el-divider/>
            <!-- 按钮 -->
            <el-form-item>
              <el-button style="width: 300px;height: 40px;margin-left: 27px" type="primary" @click="register">注册</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped>

#login {
  background-image: url('@/assets/img/loginbg.jpg');
  width: 100vw;
  height: 100vh;
  background-repeat: no-repeat;
  background-position: center;
}

#contain {
  width: 410px;
  height: 450px;
  /*居中于login*/
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /*文本居中*/
  text-align: center;
  /*透明白色圆角背景*/
  background-color: rgba(255, 255, 255);
  border-radius: 10px;
}

.textLogin {
  width: 300px;
  margin-left: 27px;
}
.s-canvas {
  cursor: pointer;
  display: inline-block;
}
.demo-tabs {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>